// Package utils @Author chenyong 2023/2/24 8:51:00
package utils

import (
	"encoding/csv"
	"fmt"
	"gitee.com/gychenyong/go-case/model"
	"os"
	"strings"
)

func WriteCsv(caseInfos []model.CaseInfo, outputFile string) {
	csvFile, err := os.Create(outputFile)
	if err != nil {
		panic(err)
	}
	defer csvFile.Close()

	writer := csv.NewWriter(csvFile)
	headLind := []string{
		Utf8ToGbk("平台"),
		Utf8ToGbk("所属模块"),
		Utf8ToGbk("用例标题"),
		Utf8ToGbk("前置条件"),
		Utf8ToGbk("步骤"),
		Utf8ToGbk("预期"),
		Utf8ToGbk("关键词"),
		Utf8ToGbk("优先级"),
		Utf8ToGbk("用例类型"),
		Utf8ToGbk("适用阶段"),
	}
	err = writer.Write(headLind)
	if err != nil {
		panic(err)
	}
	for _, caseInfo := range caseInfos {
		if caseInfo.Type == "" {
			caseInfo.Type = "功能测试"
		}
		if caseInfo.Stage == "" {
			caseInfo.Stage = "功能测试阶段"
		}

		var step string

		if len(caseInfo.StepGroups) == 1 {
			// 步骤没分组
			for stepIndex, stepName := range caseInfo.StepGroups[0].StepName {
				step = step + fmt.Sprintf("%v. %s\n", stepIndex+1, stepName)
			}
		} else {
			//步骤有分组
			for groupIndex, stepGroup := range caseInfo.StepGroups {
				step = step + fmt.Sprintf("%v. %s\n", groupIndex+1, stepGroup.GroupName)
				for stepIndex, stepName := range stepGroup.StepName {
					step = step + fmt.Sprintf("%v.%v. %s\n", groupIndex+1, stepIndex+1, stepName)
				}
			}
		}

		var expectation string

		if len(caseInfo.ExpectationGroups) == 1 {
			// 步骤没分组
			for expectationIndex, expectationName := range caseInfo.ExpectationGroups[0].ExpectationName {
				expectation = expectation + fmt.Sprintf("%v. %s\n", expectationIndex+1, expectationName)
			}
		} else {
			//步骤有分组
			for groupIndex, expectationGroup := range caseInfo.ExpectationGroups {
				expectation = expectation + fmt.Sprintf("%v. \n", groupIndex+1)
				for expectationIndex, expectationName := range expectationGroup.ExpectationName {
					expectation = expectation + fmt.Sprintf("%v.%v. %s\n", groupIndex+1, expectationIndex+1, expectationName)
				}
			}
		}

		modelName := caseInfo.Model[:strings.Index(caseInfo.Model, "(")] // 去除模块名中的ID部分，用于组合用例名称

		line := []string{
			Utf8ToGbk(""),
			Utf8ToGbk(caseInfo.Model),
			Utf8ToGbk(fmt.Sprintf("【%v】%v-%v", modelName, caseInfo.FunctionPoint, caseInfo.Title)),
			Utf8ToGbk(caseInfo.Precondition),
			Utf8ToGbk(step),
			Utf8ToGbk(expectation),
			Utf8ToGbk(""),
			Utf8ToGbk(caseInfo.Priority),
			Utf8ToGbk(caseInfo.Type),
			Utf8ToGbk(strings.Replace(caseInfo.Stage, "、", "\n", -1)),
		}

		err = writer.Write(line)
		if err != nil {
			panic(err)
		}
	}

	writer.Flush()
}
